package com.bjbn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bjbn.model.dto.BaseRequestDto;
import com.bjbn.model.dto.BaseResponseDto;
import com.bjbn.model.dto.GpsDataRequestDto;
import com.bjbn.model.dto.GpsDataResponseDto;
import com.bjbn.model.dto.HotAreaRequestDto;
import com.bjbn.model.dto.HotAreaResponseDto;
import com.bjbn.model.dto.TaxiBaseInfoRequestDto;
import com.bjbn.model.dto.TaxiBaseInfoResponseDto;
import com.bjbn.service.TransitAuthorityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 交通局API服务实现类
 */
@Service
@Slf4j
public class TransitAuthorityServiceImpl implements TransitAuthorityService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${transit-authority.base-url}")
    private String baseUrl;

    @Value("${transit-authority.api.gps-data.app-id}")
    private String gpsDataAppId;

    @Value("${transit-authority.api.gps-data.api-key}")
    private String gpsDataApiKey;

    @Value("${transit-authority.api.gps-data.app-name}")
    private String gpsDataAppName;

    @Value("${transit-authority.api.gps-data.business-id}")
    private String gpsDataBusinessId;

    @Value("${transit-authority.api.drop-off-hot.app-id}")
    private String dropOffHotAppId;

    @Value("${transit-authority.api.drop-off-hot.api-key}")
    private String dropOffHotApiKey;

    @Value("${transit-authority.api.drop-off-hot.app-name}")
    private String dropOffHotAppName;

    @Value("${transit-authority.api.drop-off-hot.business-id}")
    private String dropOffHotBusinessId;

    @Value("${transit-authority.api.pick-up-hot.app-id}")
    private String pickUpHotAppId;

    @Value("${transit-authority.api.pick-up-hot.api-key}")
    private String pickUpHotApiKey;

    @Value("${transit-authority.api.pick-up-hot.app-name}")
    private String pickUpHotAppName;

    @Value("${transit-authority.api.pick-up-hot.business-id}")
    private String pickUpHotBusinessId;

    @Value("${transit-authority.api.taxi-base-info.app-id}")
    private String taxiBaseInfoAppId;

    @Value("${transit-authority.api.taxi-base-info.api-key}")
    private String taxiBaseInfoApiKey;

    @Value("${transit-authority.api.taxi-base-info.app-name}")
    private String taxiBaseInfoAppName;

    @Value("${transit-authority.api.taxi-base-info.business-id}")
    private String taxiBaseInfoBusinessId;

    @Override
    public BaseResponseDto<GpsDataResponseDto> getGpsData(GpsDataRequestDto requestDto, String page, String pageSize) {
        log.info("获取网约车GPS数据请求: {}", JSON.toJSONString(requestDto));
        Map<String, String> params = new HashMap<>();
        params.put("app_id", gpsDataAppId);
        params.put("api_key", gpsDataApiKey);
        
        BaseRequestDto baseRequest = buildBaseRequest(gpsDataAppName, gpsDataBusinessId, page, pageSize, requestDto);
        
        return sendRequest(baseRequest, params, GpsDataResponseDto.class);
    }

    @Override
    public BaseResponseDto<HotAreaResponseDto> getDropOffHotArea(HotAreaRequestDto requestDto, String page, String pageSize) {
        log.info("获取网约车下车客流热力图数据请求: {}", JSON.toJSONString(requestDto));
        Map<String, String> params = new HashMap<>();
        params.put("app_id", dropOffHotAppId);
        params.put("api_key", dropOffHotApiKey);
        
        BaseRequestDto baseRequest = buildBaseRequest(dropOffHotAppName, dropOffHotBusinessId, page, pageSize, requestDto);
        
        return sendRequest(baseRequest, params, HotAreaResponseDto.class);
    }

    @Override
    public BaseResponseDto<HotAreaResponseDto> getPickUpHotArea(HotAreaRequestDto requestDto, String page, String pageSize) {
        log.info("获取网约车上车客流热力图数据请求: {}", JSON.toJSONString(requestDto));
        Map<String, String> params = new HashMap<>();
        params.put("app_id", pickUpHotAppId);
        params.put("api_key", pickUpHotApiKey);
        
        BaseRequestDto baseRequest = buildBaseRequest(pickUpHotAppName, pickUpHotBusinessId, page, pageSize, requestDto);
        
        return sendRequest(baseRequest, params, HotAreaResponseDto.class);
    }

    @Override
    public BaseResponseDto<TaxiBaseInfoResponseDto> getTaxiBaseInfo(TaxiBaseInfoRequestDto requestDto, String page, String pageSize) {
        log.info("获取网约车辆基础信息请求: {}", JSON.toJSONString(requestDto));
        Map<String, String> params = new HashMap<>();
        params.put("app_id", taxiBaseInfoAppId);
        params.put("api_key", taxiBaseInfoApiKey);
        
        BaseRequestDto baseRequest = buildBaseRequest(taxiBaseInfoAppName, taxiBaseInfoBusinessId, page, pageSize, requestDto);
        
        return sendRequest(baseRequest, params, TaxiBaseInfoResponseDto.class);
    }

    /**
     * 构建基础请求对象
     */
    private BaseRequestDto buildBaseRequest(String appName, String businessId, String page, String pageSize, Object data) {
        BaseRequestDto request = new BaseRequestDto();
        request.setAppName(appName);
        request.setBusinessID(businessId);
        request.setPage(page);
        request.setPageSize(pageSize);
        request.setData(data);
        return request;
    }

    /**
     * 发送HTTP请求并处理响应
     */
    @SuppressWarnings("unchecked")
    private <T> BaseResponseDto<T> sendRequest(BaseRequestDto request, Map<String, String> params, Class<T> responseType) {
        try {
            // 构建URL
            StringBuilder urlBuilder = new StringBuilder(baseUrl);
            urlBuilder.append("/dcp/api/v1/getData");
            urlBuilder.append("?app_id=").append(params.get("app_id"));
            urlBuilder.append("&api_key=").append(params.get("api_key"));
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 构建请求体
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(request), headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(urlBuilder.toString(), entity, String.class);
            
            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response.getBody());
            BaseResponseDto<T> result = new BaseResponseDto<>();
            result.setPageTotal(jsonResponse.getString("pageTotal"));
            result.setCountTotal(jsonResponse.getString("countTotal"));
            result.setPage(jsonResponse.getString("page"));
            result.setRetCode(jsonResponse.getString("retCode"));
            result.setRetMsg(jsonResponse.getString("retMsg"));
            
            // 解析数据列表
            result.setRetData(JSON.parseArray(jsonResponse.getString("retData"), responseType));
            
            log.info("请求成功，返回数据总量: {}", result.getCountTotal());
            return result;
        } catch (Exception e) {
            log.error("请求失败: {}", e.getMessage(), e);
            BaseResponseDto<T> errorResult = new BaseResponseDto<>();
            errorResult.setRetCode("500");
            errorResult.setRetMsg("请求失败: " + e.getMessage());
            return errorResult;
        }
    }
}